// Copyright (C) 2007 XtractPro (Data Extraction Magazine)
// http://www.xtractpro.com, support@xtractpro.com
//
// This code is provided AS IS, with NO WARRANTY expressed or implied.
// Any use of this free open source code is at your own risk.
//
// You are hereby granted the right to use it and change it,
// provided that you acknowledge XtractPro somewhere in your
// source files, documentation, web site and application.

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using XtractPro.Multimedia;

namespace XtractPro.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        private const string CAPTCHA_ID = "__CaptchaImage__";
        public string _result = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["captcha"] == "true")
                GetCaptchaImage();
            else
            {
                if (IsPostBack)
                    _result = (IsValidCaptcha() ? "Valid Code" : "Invalid Code");
                CreateCaptchaImage();
            }
        }

        /// <summary>
        /// Renders IMG SRC content for the client-side CAPTCHA image
        /// </summary>
        private void GetCaptchaImage()
        {
            CaptchaImage image = Session[CAPTCHA_ID] as CaptchaImage;
            Debug.Assert(image != null);
            Response.Clear();
            Response.ContentType = "image/jpeg";
            image.Image.Save(Response.OutputStream, ImageFormat.Jpeg);
        }

        // Generate a new CaptchaImage instance, with custom values
        private void CreateCaptchaImage()
        {
            CaptchaImage image = new CaptchaImage();
            Session[CAPTCHA_ID] = image;

            // customize CaptchaImage instance here
            image.CharacterSet = "BCDFGHJKLMNPQRSTVWXYZ";
        }

        // Returns true if valid entered code (case insensitive comparison!)
        private bool IsValidCaptcha()
        {
            CaptchaImage image = Session[CAPTCHA_ID] as CaptchaImage;
            return (String.Compare(image.Text, CaptchaCode.Text, true) == 0);
        }
    }
}